package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.ArrayProblem;

/**
 * https://leetcode.com/problems/first-missing-positive/
 * <p>
 * 也是链表数组法, see LC448
 * - 第一个洞见: 答案的整数, 必是 1到n+1 范围内的!
 *
 * @author tzp
 * @since 2020/10/16
 */
public class LC41 implements ArrayProblem {
    public int firstMissingPositive(int[] nums) {
        if (nums == null || nums.length == 0) return 1;
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i + 1 && validIndexInCell(nums, i) && nums[i] != nums[nums[i] - 1]) {
                swap(nums, i, nums[i] - 1);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) return i + 1;
        }
        return nums.length + 1;
    }

    public boolean validIndexInCell(int[] nums, int i) {
        return nums[i] > 0 && nums[i] <= nums.length;
    }

    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    public static void main(String[] args) {
        System.out.println(new LC41().firstMissingPositive(new int[]{1}));
        System.out.println(new LC41().firstMissingPositive(new int[]{1, 2, 0}));
        System.out.println(new LC41().firstMissingPositive(new int[]{3, 4, -1, 1}));
        System.out.println(new LC41().firstMissingPositive(new int[]{7, 8, 9, 10}));
    }
}
